package com.joven.shelltest.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joven.shelltest.dto.CommentsDto;
import com.joven.shelltest.dto.RootCommentsDto;
import com.joven.shelltest.entity.Comments;
import com.joven.shelltest.mapper.CommentsMapper;
import com.joven.shelltest.service.CommentsService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 评论索引表 服务实现类
 * </p>
 *
 * @author joven
 * @since 2024-11-08
 */
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements CommentsService {

    @Override
    public List<RootCommentsDto> getCommentsByArticleId(Long id) {
        List<CommentsDto> oriResult = this.baseMapper.getCommentsList(id);
        List<RootCommentsDto> rootComments = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(oriResult)) {
            List<RootCommentsDto> temp = new ArrayList<>();
            oriResult.forEach(data -> {
                RootCommentsDto rootCommentsDto = new RootCommentsDto();
                BeanUtil.copyProperties(data, rootCommentsDto);
                temp.add(rootCommentsDto);
            });

            Map<Long, RootCommentsDto> commentMap = temp.stream()
                    .collect(Collectors.toMap(RootCommentsDto::getCommentId, comment -> comment));

            for (RootCommentsDto comment : temp) {
                if (comment.getParentId() == 0) {
                    rootComments.add(comment);
                } else {
                    RootCommentsDto parent = commentMap.get(comment.getParentId());
                    if (parent != null) {
                        if (CollectionUtils.isNotEmpty(parent.getChildren())) {
                            parent.getChildren().add(comment);
                        } else {
                            List<RootCommentsDto> children = new ArrayList<>();
                            children.add(comment);
                            parent.setChildren(children);
                        }

                    }
                }
            }
        }
        return rootComments;
    }

}
